package cn.tiltglass.service.impl;

import cn.tiltglass.client.FastDfsClient;
import cn.tiltglass.client.RedisClient;
import cn.tiltglass.domain.PageConfig;
import cn.tiltglass.domain.Pager;
import cn.tiltglass.mapper.PageConfigMapper;
import cn.tiltglass.mapper.PagerMapper;
import cn.tiltglass.service.IPageConfigService;
import cn.tiltglass.util.AjaxResult;
import cn.tiltglass.utils.VelocityUtils;
import cn.tiltglass.utils.ZipUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import feign.Response;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiltglass
 * @since 2020-02-24
 */
public class PageConfigServiceImpl_bak extends ServiceImpl<PageConfigMapper, PageConfig> implements IPageConfigService {


    @Autowired
    private PagerMapper pagerMapper;

    @Autowired
    private FastDfsClient fastDfsClient;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private PageConfigMapper pageConfigMapper;
    //正在做页面静态化
    @Override      //courseTypes- xxx jobTypes=yyy
    public void staticPage(String pageName, String dataKey){
        InputStream inputStream = null;
        FileOutputStream os = null;
        try{
            //一 通过pageName获取Page并从中获取模板 url（zip）+name(home.vm)
            //1.1 查询page对象
            List<Pager> pagers = pagerMapper.selectList(new EntityWrapper<Pager>().eq("name", pageName));
            if (pagers == null || pagers.size()<1) return;
            Pager pager = pagers.get(0);
            //1.2 获取模板zip包，它是fastdfs的地址
            String templateUrl = pager.getTemplateUrl();
            //1.3 使用fastdfsclient下载它
            Response response = fastDfsClient.download(templateUrl);
            inputStream = response.body().asInputStream();
            String tmpdir=System.getProperty("java.io.tmpdir"); //跨操作系统
            String unzipFile = tmpdir+"/temp.zip";
            os = new FileOutputStream(unzipFile);
            IOUtils.copy(inputStream, os);
            System.out.println("下载路径:" + unzipFile);
            //1.4 解压缩
            String unzipDir = tmpdir+"/temp/";
            ZipUtil.unzip(unzipFile,unzipDir);
            System.out.println("解压路径:" + unzipDir);
            //1.5 解压路径拼接模板名称得到完整的模板地址
            String tempatePath = unzipDir+"/"+pager.getTemplateName(); //c://temp/home.vm
            System.out.println("模板路径:" + tempatePath);
            //二  通过dataKey获取数据
            //{"courseTypes":[]}
            String jsonStr = redisClient.get(dataKey);
            Map model = JSONObject.parseObject(jsonStr,Map.class); //获取传递的map数据
            //{"courseTypes":[],"staticRoot":"xxx"}
            model.put("staticRoot",unzipDir); // 往map里面追加参数
            //三  做页面静态化到本地
            String staticPath = tempatePath+".html";//c://temp/home.vm.html
            System.out.println("静态化页面地址："+staticPath);
            VelocityUtils.staticByTemplate(model,tempatePath,staticPath);

            //四 把静态化好的页面上传到fastdfs
            AjaxResult ajaxResult = fastDfsClient
                    .upload(new CommonsMultipartFile(createFileItem(new File(staticPath))));

            //五 存放pageConfig
            PageConfig pageConfig = new PageConfig();
            pageConfig.setTemplateUrl(templateUrl);
            pageConfig.setTemplateName(pager.getTemplateName());
            pageConfig.setDataKey(dataKey);
            pageConfig.setPhysicalPath(pager.getPhysicalPath());
            pageConfig.setDfsType(0L); //0表示fastDfs
            pageConfig.setPageUrl((String) ajaxResult.getResultObj()); //上传完的地址
            pageConfig.setPageId(pager.getId());
            pageConfigMapper.insert(pageConfig);
            //@TODO 六 发送Message到mq中
        }catch (Exception e){
            e.printStackTrace();
        }finally {

            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    /*
创建FileItem
*/
    private FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        FileItem item = factory.createItem("file", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

}
